<?php

namespace App\Admin\Controllers\Videos;

use App\Admin\Repositories\VideoCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Cache;

class VideoCategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new VideoCategory(), function (Grid $grid) {
            $grid->model()->orderBy('sort');
            $grid->column('id')->sortable();
            $grid->column('name')->editable();
            $grid->column('img')->image(80, 80);
            $grid->column('sort')->editable()->sortable();
            $grid->column('state')->switch()->sortable();
            $grid->column('created_at')->sortable();
            $grid->column('updated_at')->sortable();
        
            $grid->enableDialogCreate();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new VideoCategory(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('img');
            $show->field('state');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new VideoCategory(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->text('img');
            // $form->radio('state')->options([1 => '启用',-1=>'停用'])->default(1);
            $form->number('sort')->default(0);
            $form->switch('state')->default(1);
            $form->display('created_at');
            $form->display('updated_at');

            $form->saved(function(Form $form){
                Cache::forget('categories');
            });

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
            
                // 通过 $result 可以判断数据是否删除成功
                if (! $result) {
                    return $form->response()->error('数据删除失败');
                }
                Cache::forget('categories');
                // 返回删除成功提醒，此处跳转参数无效
                return $form->response()->success('删除成功');
            });
        });
    }
}
